<?php

namespace backend\controllers;

use Yii;
use backend\models\PayLogistics;
use backend\models\PayLogisticsSearch;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
use backend\models\ItemPreview;
use backend\models\Image;
use common\models\UserInfo;
use common\models\UserAddress;
use yii\web\ForbiddenHttpException;
use backend\models\AdminInfo;
use yii\web\UploadedFile;
use liangzoe\mobilesmser\TextSmser;
use backend\models\SysItem;
use backend\models\GrpBrand;
use backend\models\PayTrade;
use common\models\SmsLogRecord;
use yii\db\ActiveRecord;
use yii\helpers\Url;
use backend\models\SysItemPrices;

require dirname(dirname(__FILE__)).'/web/phpexcel/PHPExcel.php';

/**
 * PayLogisticsController implements the CRUD actions for PayLogistics model.
 */
class PayLogisticsController extends Controller
{
    public function behaviors()
    {
        return [
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'delete' => ['post'],
                ],
            ],
        ];
    }
    public function beforeAction($action)
    {
    	//如果未登录，则直接跳转
    	if(Yii::$app->user->isGuest){
    		return $this->redirect(['/site/login']);
    	}
    	
    	 
    	$action = Yii::$app->controller->action->id;
    	$controller = Yii::$app->controller->id;
    	if(\Yii::$app->user->can('pay-logistics')){
    		return true;
    	}else{
    		throw new ForbiddenHttpException(Yii::t('app','Sorry , You don\'t have permission'));
    	}
    }
    /**
     * Lists all PayLogistics models.
     * @return mixed
     */
    public function actionIndex()
    {
        $searchModel = new PayLogisticsSearch();
        $dataProvider = $searchModel->search(Yii::$app->request->queryParams);

        //print_r($dataProvider);return;
        return $this->render('index', [
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider,
        ]);
    }
    /**
     * 众筹采购管理
     */
    public function actionCrowdindex(){
        $searchModel = new PayLogisticsSearch();
        $dataProvider = $searchModel->crowdsearch(Yii::$app->request->queryParams);
        
        //print_r($dataProvider);return;
        return $this->render('crowd_index', [
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider,
        ]);
    }
    //财务待打款
    public function actionFinancePay()
    {
        $searchModel = new PayLogisticsSearch();
        $dataProvider = $searchModel->search(Yii::$app->request->queryParams,true);
        return $this->render('dunning_index', [
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider,
        ]);
    }
    
    /**
     * 众筹采购付款
     */
    public function actionCrowdFinancePay(){
        $searchModel = new PayLogisticsSearch();
        $dataProvider = $searchModel->crowdsearch(Yii::$app->request->queryParams,true);
        
        return $this->render('crowd-dunning_index', [
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider,
        ]);
    }
    //催收货
    public function actionDelivery()
    {
        $searchModel = new PayLogisticsSearch();
        $searchModel->logistics_state=1;
        $dataProvider = $searchModel->search(Yii::$app->request->queryParams);
        
        return $this->render('delivery_index', [
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider,
        ]);
    }
    
    /**
     * 众筹待收货
     * @return unknown
     */
    public function actionCrowdDelivery(){
        $searchModel = new PayLogisticsSearch();
        $searchModel->logistics_state=1;
        $dataProvider = $searchModel->crowdsearch(Yii::$app->request->queryParams);
        return $this->render('crowd-delivery_index', [
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider,
        ]);
    }
    /**
     * Displays a single PayLogistics model.
     * @param integer $id
     * @return mixed
     */
    public function actionView($id,$trade_id,$brand_id)
    {

    	$arr_item_model = $this->get_item_data($trade_id, $brand_id);
    	$item_model = $arr_item_model['item_model'];
    	//查看当前订单类型
    	$payTrade=PayTrade::findOne($trade_id);
    	$trade_class=$payTrade->trade_class;
        return $this->render('view', [
        		'trade_id'=>$trade_id,
        		'brand_id'=>$brand_id,
            	'model' => $this->findModel($id),
        		'item_model'=>$item_model,
                 'trade_class'=>$trade_class
        		
        ]);
    }

    /**
     * Creates a new PayLogistics model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     * @return mixed
     */
    public function actionCreate()
    {
        $model = new PayLogistics();

        if ($model->load(Yii::$app->request->post()) && $model->save()) {
            return $this->redirect(['view', 'id' => $model->id]);
        } else {
            return $this->render('create', [
                'model' => $model,
            ]);
        }
    }
	public function save_file($model){
		$uuid = md5(uniqid());
		$date = date('Y-m-d',time());
		$folder = Yii::getAlias('@webroot').'/finance/'.$date;
		TextSmser::make_dir($folder);
		$file_addr = $folder.'/'.$uuid.'.'.$model->file->extension;
		$model->file->saveAs($file_addr);
		return 'finance/'.$date.'/'.$uuid.'.'.$model->file->extension;
		
	}
	/**
	 * 更新单品的成本价
	 */
	public function actionSetCostprice($trade_id,$brand_id,$all_price_list){
		$arr_item_model = $this->get_item_data($trade_id, $brand_id);
		$ask_cost_price=0;
		$_logistics_ids = implode(',',$arr_item_model['_arr_logistics_ids']);//logistics_id
		$_price_list = explode('@', $all_price_list);
		foreach ($_price_list as $key=>$val){
			$_price_arr = explode('|', $val);$_cost_price = $_price_arr[0];$_item_id= $_price_arr[1];	
			$sql = "select * from pay_logistics where id in({$_logistics_ids}) and item_id={$_item_id}";
			$_change_model = PayLogistics::findBySql($sql)->one();
			$_item_memo_arr=json_decode($_change_model['item_memo'],true);//转为数组
			$_item_memo_arr['cost_price']=$_cost_price;
			$_item_memo = json_encode($_item_memo_arr);//重新组合的json字符串
			$_change_model->item_memo = $_item_memo;
			$ask_cost_price += $_cost_price;
			$update = $_change_model->save();
			//if(!$update) continue;
		}
		$update_data['ask_cost_price'] = $ask_cost_price;
		PayLogistics::updateAll($update_data,"id in ({$_logistics_ids})");//批量更新
		echo json_encode(array('error'=>false,'msg'=>'成本价更新成功'));
	}
    /**更新发货单
     * Updates an existing PayLogistics model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param integer $id
     * @return mixed
     */
    public function actionUpdate($id,$trade_id,$brand_id)
    {
        if (!(Yii::$app->user->can('paylogistics-update') || Yii::$app->user->can('paylogistics-audit')) ){
            throw new ForbiddenHttpException(Yii::t('app','Sorry , You don\'t have permission'));
            return;
        }
    	$arr_item_model = $this->get_item_data($trade_id, $brand_id);
    	$item_model = $arr_item_model['item_model'];
    	$sales_service = $arr_item_model['sales_service'];
    	$user_discount = $arr_item_model['user_discount'];
    	$_arr_logistics_ids = $arr_item_model['_arr_logistics_ids'];
    	//运营商地址
    	$operation_model=UserInfo::find()->joinWith(['useraddress'])->where('user_type=5')->all();
    	//var_dump($operation_model);
    	//物流信息
        $model = $this->findModel($id);     
        $model_old = $this->findModel($id);
        if (Yii::$app->request->isPost && $model->load(Yii::$app->request->post())) {
        	if($model->apply_pay > $model->ask_cost_price - $model->payed) 
        	{
        		echo '<script type="text/javascript">';
        		echo 'alert("申请金额不能大于未支付金额");';
        		echo 'history.back(-1);';
        		echo '</script>';
        		return ;
        	}
        	$update_data = array(
        		//	'logistics_trade'=>$model->logistics_trade,
        			'logistics_message'=>'',
        			'logistics_name'=>$model->logistics_name,
        			'logistice_price'=>$model->logistice_price,
        			'send_address'=>$model->send_address,
        			'send_photo'=>$model->send_photo,
        			'accept_address'=>$model->accept_address,
        			'accept_photo'=>$model->accept_photo,
        			'operation_address'=>$model->operation_address,
        			'operation_photo'=>$model->operation_photo,        			
        			'ask_cost_price'=>$model->ask_cost_price,
        		//	'apply_pay'=>$model->apply_pay,
        		//	'audit_pay'=>$model->audit_pay,
        		//	'actual_pay'=>$model->actual_pay,
        	);
        	if(!empty($model->write_notes)){
        		$update_data['notes'] = $model->notes.';<br/>'.$model->write_notes;
        	}
        	//选择运营商
        	if(!empty($model->operation_address_select)){
        		
        		$operation_address = UserAddress::findOne(['uid'=>$model->operation_address_select,'type'=>1]);//默认地址
        		$update_data['operation_address']=$operation_address['area'].$operation_address['address'].' '.$operation_address['postcode'].'('.$operation_address['name'].')'.'('.$model->operation_address_select.')';
        		$update_data['operation_photo']=$operation_address['mobile'];
        		$update_data['operation_uid']=$model->operation_address_select;
        	}
        	//支付相关时间
        	$_arr_audit = array('1'=>'同意','2'=>'不同意');
        	if($model->apply_pay != '0.00' && $model->audit_pay == '0'){
        		$update_data['doing'] = 1;
        	}
      //  	echo $model->apply_pay;echo $model_old->apply_pay;
        	if($model->audit_pay == '0' && $model->apply_pay != '0.00'){//未审核才能修改
        		$update_data['apply_pay']=$model->apply_pay;$update_data['apply_pay_time'] = time();
        		$update_data['apply_pay_uid'] = Yii::$app->user->identity->id;
        	}
        	
        	if($model->audit_pay == '1'){//只能审核一次,审核通过
        		$update_data['audit_pay']=$model->audit_pay;$update_data['audit_pay_time'] = time();
        		$update_data['audit_pay_uid'] = Yii::$app->user->identity->id;$update_data['doing'] = 2;
        	}
        	if($model->audit_pay == '2'){//审核不同意，结束
        		$update_data['pay_done_list'] = $model->pay_done_list . $model->apply_pay.'元|'.date('Y-m-d H:i:s',$model->apply_pay_time).'|'.AdminInfo::getUsernameById($model->apply_pay_uid)['username']
        		.','.$_arr_audit[$model->audit_pay].'|'.date('Y-m-d H:i:s',time()).'|'.AdminInfo::getUsernameById(Yii::$app->user->identity->id)['username']
        		.'<br/>';
        		
        		$update_data['doing'] = 0;//数据清空
        		$update_data['apply_pay']=0.00;
        		$update_data['apply_pay_time']=0;
        		$update_data['apply_pay_uid']=0;
        		$update_data['audit_pay']=0;
        		$update_data['audit_pay_time']=0;
        		$update_data['audit_pay_uid']=0;
        		
        	}
        	if($model_old->actual_pay != $model->actual_pay && $model->audit_pay == '1'){//财务打款
        		// 上传转账凭证
        		$model->file = UploadedFile::getInstance($model, 'file');
        		if(!empty($model->file)){
            		$file_addr = $this->save_file($model);        		    
        			$update_data['actual_pay_file'] = !empty($model->actual_pay_file)?$model->actual_pay_file.'|'.$file_addr:$file_addr;
        		}
        		$update_data['actual_pay'] = $model->actual_pay;$update_data['actual_pay_time'] = time();
        		$update_data['actual_pay_uid'] = Yii::$app->user->identity->id;
        		$update_data['pay_done_list'] = $model->pay_done_list . $model->apply_pay.'元|'.date('Y-m-d H:i:s',$model->apply_pay_time).'|'.AdminInfo::getUsernameById($model->apply_pay_uid)['username']
        								.','.$_arr_audit[$model->audit_pay].'|'.date('Y-m-d H:i:s',$model->audit_pay_time).'|'.AdminInfo::getUsernameById($model->audit_pay_uid)['username']
        								.','.$model->actual_pay.'|'.date('Y-m-d H:i:s',time()).'|'.Yii::$app->user->identity->username
        								.(empty($model->file)?'':'<a href="'.$file_addr.'" target="_blank">&nbsp;&nbsp;财务凭证</a>'.'<br/>');
        		//打款后更新已打款金额
        		$update_data['payed']=$model->payed + $model->apply_pay;
        		$update_data['doing'] = 0;//数据清空
        		$update_data['apply_pay']=0.00;
        		$update_data['apply_pay_time']=0;
        		$update_data['apply_pay_uid']=0;
        		$update_data['audit_pay']=0;
        		$update_data['audit_pay_time']=0;
        		$update_data['audit_pay_uid']=0;
        		$update_data['actual_pay']='';
        		$update_data['actual_pay_time']=0;
        		$update_data['actual_pay_uid']=0;
		
        	}

        	if(empty($model_old->logistics_trade) && !empty($model->logistics_trade)){
        		$trade_model = PayTrade::findOne(['id'=>$trade_id]);
        		if($trade_model->price_state == 11){
        			echo '<script type="text/javascript">';
        			echo 'alert("订单还没全部支付，不能发货");';
        			echo 'history.back(-1);';
        			echo '</script>';
        			return ;
        		}
        		$update_data['logistics_trade']=$model->logistics_trade;
        		$update_data['logistics_state']=1;
        		$update_data['admin_uid']=Yii::$app->user->identity->id;
        		$update_data['admin_time']=time();
        		$update_data['send_time']=time();//发货时间     		
        	}
        	if(empty($model->logistics_no)){//第一次更新时，生成单号
        		$update_data['logistics_no']= date('YmdHis',time()).time().rand(10, 99);
        	}
        	if(empty($model_old->deliver_time) && !empty($model->deliver_time_1)){
        		$update_data['deliver_time'] = strtotime($model->deliver_time_1);
        	}
        	$update_data['logistics_message'] = $model->logistics_message;
			$_logistics_ids = implode(',', $_arr_logistics_ids);
			
        	PayLogistics::updateAll($update_data,"id in ({$_logistics_ids})");//批量更新
        	
        	//物流单号都填，更改trade为发货
        	if(empty($model_old->logistics_trade) && !empty($model->logistics_trade)){
	        	$_logistics_trade = PayLogistics::find()->where("trade_id={$trade_id} and logistics_trade =''")->all();
	        	
	        	if(!$_logistics_trade ){
	        		$trade_model = PayTrade::findOne(['id'=>$trade_id]);
	        		$trade_model->trade_state=7;
	        		$trade_model->save();
	        		
	        		$msg = "您的订单（{$trade_model->trade_no}）已经发货，请留意货运信息，签收后请打开APP确认收货。".' 退订回复TD';
	        		$smser = new TextSmser();
	        		$smser->sendSMSbatch($trade_model->userInfo['tel'], $msg);
	        		$model_log = new SmsLogRecord();
	        		$model_log->send_uid = Yii::$app->user->identity->id;
	        		$model_log->accept_uid = $trade_model->user_id;
	        		$model_log->send_content = $msg;
	        		$model_log->send_time = time();
	        		$model_log->save();
	        	}
        	}
        	
        	//调用快递订阅接口
        	if ($model->logistics_name!='other' && $model->logistics_trade != null)
        	{
        	    //$url="http://poll.kuaidi100.com/poll";
				$url="http://www.kuaidi100.com/poll";
        	    $param=[
        	        'company'=>$model->logistics_name,
        	        'number'=>$model->logistics_trade,
        	        'key'=>'YjPgYUqw7427',
        	        'parameters'=>[
        	            'callbackurl'=>'http://www.'.Yii::$app->params['site_url'].Url::to(['callback/kuaidi']),
        	            'resultv2'=>'1'
        	        ]
        	    ];
        	    $post_data='schema=json&param='.json_encode($param,JSON_UNESCAPED_UNICODE);
        	    $kuaidiRequestResult=self::curlRequest($url, $post_data);
        	    $kuaidiRequestResult=json_decode($kuaidiRequestResult,true);
        	    if (!$kuaidiRequestResult['result'])
        	    {
        	        echo '快递订阅出错，原因：';
        	        switch ($kuaidiRequestResult['returnCode'])
        	        {
        	            case '701':echo '拒绝订阅的快递公司';break;
        	            case '700':echo '订阅方的订阅数据存在错误（如不支持的快递公司、单号为空、单号超长等）或错误的回调地址';break;
        	            case '702':echo 'POLL:识别不到该单号对应的快递公司';break;
        	            case '600':echo '您不是合法的订阅者（即授权Key出错）';break;
        	            case '601':echo 'POLL:KEY已过期';break;
        	            case '500':echo '服务器错误（即快递100的服务器出理间隙或临时性异常，有时如果因为不按规范提交请求，比如快递公司参数写错等，也会报此错误）';break;
        	            case '501':echo '重复订阅';break;
        	        }
        	        print_r($kuaidiRequestResult);
        	        return;
        	    }
        	}
        	
           return $this->redirect(['view', 'id' => $model->id,'trade_id'=>$trade_id,'brand_id'=>$brand_id]);
          
        	
        } else {
       
            $kuaidi=ActiveRecord::findBySql("select code,`name` from grp_kuaidi where use_flag = 1")->asArray()->all();
            $kuaidi[count($kuaidi)]=[
                'code'=>'other',
                'name'=>'其他快递'
            ];
            return $this->render('update', [
                'model' => $model,
            	'item_model'=>$item_model,
            	'operation_model'=>$operation_model,
            	'sales_service'=>$sales_service,
                'kuaidi' => $kuaidi
            ]);
        }
    }
    /**
     * 厂商进价改价申请
     * @return string
     */
    function actionApplyAsk_cost_price(){
    	
    	$res = array('error'=>false,'msg'=>'');
    	if(\Yii::$app->user->can('paylogistics-update')){
	    	$arr_item_model = $this->get_item_data($_POST['trade_id'], $_POST['brand_id']);
	    	$_arr_logistics_ids = $arr_item_model['_arr_logistics_ids']; 	
	    	$ask_cost_price_list = $arr_item_model['item_model'][0]['ask_cost_price_list'];
	    	$ask_cost_price = $arr_item_model['item_model'][0]['ask_cost_price'];//厂家进价
	    	$payed = $arr_item_model['item_model'][0]['payed'];//已支付金额
	    	$_logistics_ids = implode(',', $_arr_logistics_ids);
	    	
	    	if($ask_cost_price == $payed){//已支付金额=厂家进价不能修改
	    		$res['error'] = true;
	    		$res['msg'] = '修改失败：已支付金额等于厂家进价';
	    	}elseif($payed > $_POST['result']){//改价不能小于已支付金额
	    		$res['error'] = true;
	    		$res['msg'] = '修改失败：改价小于已支付金额';    	
	    	}elseif(is_numeric($_POST['result']) && $_POST['result']>0){
		    	$update_data['ask_cost_price_0']=round($_POST['result']);
		    	$_str = '改价申请|'.date('Y-m-d H:i:s').'|user_id:'.Yii::$app->user->identity->id.'，';
		    	$update_data['ask_cost_price_list'] = $ask_cost_price_list.$_str;
		    	$update_data['ask_cost_price_status'] = 1;//申请审核
		    	
		    	PayLogistics::updateAll($update_data,"id in ({$_logistics_ids})");//批量更新
		    	$res['msg']='已申请';
	    	}else{
	    		$res['error'] = true;
	    		$res['msg'] = '操作错误';
	    	}
    	}else{
    		$res['error'] = true;
    		$res['msg']   = '没有权限';
    	}
    	return json_encode($res);
    }
    /**
     * 手动改价审核
     * @return string
     */
    function actionAuditAsk_cost_price(){
    	$res = array('error'=>false,'msg'=>'');
    	if(\Yii::$app->user->can('paylogistics-audit')){
	    	$arr_item_model = $this->get_item_data($_POST['trade_id'], $_POST['brand_id']);
	    	$ask_cost_price_list = $arr_item_model['item_model'][0]['ask_cost_price_list'];
	    	$_arr_logistics_ids = $arr_item_model['_arr_logistics_ids'];
	    	$_logistics_ids = implode(',', $_arr_logistics_ids);
			
	    	$update_data = array();
	    	if($_POST['ask_cost_price_0'] <= 0){
	    		$res['error'] = true;
	    		$res['msg'] = '改价需大于0';
	    	}elseif($_POST['result'] == 'true'){
	    		$update_data['ask_cost_price']=$_POST['ask_cost_price_0'];
	    		$update_data['ask_cost_price_0']=0;
	    		$_str = '改价通过|'.date('Y-m-d H:i:s').'|user_id:'.Yii::$app->user->identity->id.'<br/>';
	    		$update_data['ask_cost_price_list'] = $ask_cost_price_list.$_str;
	    		$update_data['ask_cost_price_status'] = 2;//审核通过
	    		PayLogistics::updateAll($update_data,"id in ({$_logistics_ids})");//批量更新
	    		$res['msg']='已通过审核';
	    	}elseif($_POST['result'] == 'false'){
	    		$_str = '改价未通过:'.$_POST['reason'].'|'.date('Y-m-d H:i:s').'|user_id:'.Yii::$app->user->identity->id.'<br/>';
	    		$update_data['ask_cost_price_list'] = $ask_cost_price_list.$_str;
	    		$update_data['ask_cost_price_status'] = 3;//审核未通过
	    		PayLogistics::updateAll($update_data,"id in ({$_logistics_ids})");//批量更新
	    		$res['error'] = true;
	    		$res['msg']='未通过审核';
	    	}else{
	    		$res['error'] = true;
	    		$res['msg'] = '操作错误';
	    	}
    	}else{
    		$res['error'] = true;
    		$res['msg']   = '没有权限';
    	}
    	return json_encode($res);
    }
    /**
     * 按钮自动改价
     */
    function actionAutoAsk_cost_price(){
    	$res = array('error'=>false,'msg'=>'');
    	if(\Yii::$app->user->can('paylogistics-update')){
    		$this->get_item_data($_POST['trade_id'], $_POST['brand_id'],true);
    		$res['msg'] = '自动改价成功';
    	}else{
    		$res['error'] = true;
    		$res['msg']   = '没有权限';
    	}
    	return json_encode($res);
    	
    }
    /**
     *
     * @param unknown $url
     * @param unknown $post_data
     * @return mixed
     */
    private static function curlRequest($url,$post_data)
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
        $output = curl_exec($ch);
        curl_close($ch);
        return $output;
    }
    public function actionPrintOrder($id,$trade_id,$brand_id){
    	
    	$arr_item_model = $this->get_item_data($trade_id, $brand_id);
    	$Data = $arr_item_model['item_model'];
    	$model=$this->findModel($id);
    	
    	//include(ROOT_PATH . '/external/widgets/phpexcel/PHPExcel.php');
    	
    	// Create new PHPExcel object
    	$objPHPExcel = new \PHPExcel();
    	//实例化图片处理类
    	
    	// Set properties
    	$objPHPExcel->getProperties()->setCreator("ctos")
    	->setLastModifiedBy("ctos")
    	->setTitle("Office 2007 XLSX Test Document")
    	->setSubject("Office 2007 XLSX Test Document")
    	->setDescription("Test document for Office 2007 XLSX, generated using PHP classes.")
    	->setKeywords("office 2007 openxml php")
    	->setCategory("Test result file");
    	//set width
    	$objPHPExcel->getActiveSheet()->getColumnDimension('A')->setWidth(20);
    	$objPHPExcel->getActiveSheet()->getColumnDimension('B')->setWidth(30);
    	$objPHPExcel->getActiveSheet()->getColumnDimension('C')->setWidth(25);
    	$objPHPExcel->getActiveSheet()->getColumnDimension('D')->setWidth(30);
    	$objPHPExcel->getActiveSheet()->getColumnDimension('E')->setWidth(50);
    	$objPHPExcel->getActiveSheet()->getColumnDimension('F')->setWidth(30);
    	$objPHPExcel->getActiveSheet()->getColumnDimension('G')->setWidth(12);
    	
    	$objPHPExcel->setActiveSheetIndex(0)->getColumnDimension('H')->setWidth(50);
    	//设置行高度
    	$objPHPExcel->getActiveSheet()->getRowDimension('1')->setRowHeight(22);
    	$objPHPExcel->getActiveSheet()->getRowDimension('2')->setRowHeight(30);
    	//set font size bold
    	$objPHPExcel->getActiveSheet()->getDefaultStyle()->getFont()->setSize(10);
    	$objPHPExcel->getActiveSheet()->getStyle('A1:H1')->getFont()->setBold(true);
    	 
    	$objPHPExcel->getActiveSheet()->getStyle('A1:H1')->getAlignment()->setVertical(\PHPExcel_Style_Alignment::VERTICAL_CENTER);
    	$objPHPExcel->getActiveSheet()->getStyle('A1:H1')->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
    	$objPHPExcel->getActiveSheet()->getStyle('A1:H1')->getBorders()->getAllBorders()->setBorderStyle(\PHPExcel_Style_Border::BORDER_THIN);
    	//设置水平居中
    	//$objPHPExcel->getActiveSheet()->getStyle('A1')->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_LEFT);
    	$objPHPExcel->getActiveSheet()->getStyle('A')->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
    	$objPHPExcel->getActiveSheet()->getStyle('B')->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
    	$objPHPExcel->getActiveSheet()->getStyle('C')->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
    	$objPHPExcel->getActiveSheet()->getStyle('D')->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
    	$objPHPExcel->getActiveSheet()->getStyle('E')->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
    	$objPHPExcel->getActiveSheet()->getStyle('F')->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
    	$objPHPExcel->getActiveSheet()->getStyle('G')->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
    	$objPHPExcel->getActiveSheet()->getStyle('H')->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
    	
    	$objPHPExcel->getActiveSheet()->getStyle('G')->getNumberFormat()->setFormatCode('0.00');
    	//合并cell
    	//	$objPHPExcel->getActiveSheet()->mergeCells('A1:M1');//标题行
    	 
    	// set table header content
    	$objPHPExcel->setActiveSheetIndex(0)
    	//	->setCellValue('A1', '机构对账（养老） 搜索条件：月份（'.$date_keyword.'），机构（'.$merchant_keyword.'），导出 时间:'.date('Y-m-d H:i:s'))
    	->setCellValue('A1', '名称')
    	->setCellValue('B1', '图片')
    	->setCellValue('C1', '面料')
    	->setCellValue('D1', '面料图片')
    	->setCellValue('E1', '材质')
    	->setCellValue('F1', '材质图片')
    	->setCellValue('G1', '实际价格');

    	// Miscellaneous glyphs, UTF-8
    	 
    	for($i=0;$i<count($Data);$i++){
    		
    		$objPHPExcel->getActiveSheet(0)->setCellValue('A'.($i+2), $Data[$i]['name']);
    	//	$objPHPExcel->getActiveSheet(0)->setCellValue('B'.($i+2), $Data[$i]['preview_img_url']);
    		$objPHPExcel->getActiveSheet(0)->setCellValue('C'.($i+2), $Data[$i]['fab_name']);
    	//	$objPHPExcel->getActiveSheet(0)->setCellValue('D'.($i+2), $Data[$i]['fab_img_url']);
    		$objPHPExcel->getActiveSheet(0)->setCellValue('E'.($i+2), $Data[$i]['mat_name']);
    	//	$objPHPExcel->getActiveSheet(0)->setCellValue('F'.($i+2), $Data[$i]['mat_img_url']);
    		$objPHPExcel->getActiveSheet(0)->setCellValue('G'.($i+2), $Data[$i]['final_price']);
    		//$objPHPExcel->getActiveSheet(0)->setCellValueExplicit('G'.($i+2), $Data[$i]['final_price'],\PHPExcel_Cell_DataType::TYPE_STRING);

    		$_arr_img = array();
    		if($Data[$i]['preview_img_url'] != '') $_arr_img[]=array('url'=>$Data[$i]['preview_img_url'],'cell'=>'B'.($i+2));
    		if($Data[$i]['fab_img_url'] !='') $_arr_img[]=array('url'=>$Data[$i]['fab_img_url'],'cell'=>'D'.($i+2));
    		if($Data[$i]['mat_img_url'] !='') $_arr_img[]=array('url'=>$Data[$i]['mat_img_url'],'cell'=>'F'.($i+2));
    		foreach ($_arr_img as $val){
    			$objDrawing = new \PHPExcel_Worksheet_Drawing();		  			
    			/*设置图片所在单元格的格式*/
    			$objDrawing->setOffsetX(80);
    			$objDrawing->setRotation(20);
    			$objDrawing->getShadow()->setVisible(true);
    			$objDrawing->getShadow()->setDirection(50);
    			$objDrawing->setPath($val['url']);
    			/*设置图片要插入的单元格*/
    			$objDrawing->setCoordinates($val['cell']);
    			/*设置图片宽度高度*/
    			$objDrawing->setHeight(60);
    			$objDrawing->setWidth(60);
    			$objDrawing->setWorksheet($objPHPExcel->getActiveSheet());
    		}
    			
    		$objPHPExcel->getActiveSheet()->getStyle('A'.($i+2).':G'.($i+2))->getAlignment()->setVertical(\PHPExcel_Style_Alignment::VERTICAL_CENTER);
    		$objPHPExcel->getActiveSheet()->getStyle('A'.($i+2).':G'.($i+2))->getBorders()->getAllBorders()->setBorderStyle(\PHPExcel_Style_Border::BORDER_THIN);
    		$objPHPExcel->getActiveSheet()->getRowDimension($i+2)->setRowHeight(50);
    	}
    	 
    	//  sheet命名
    	$objPHPExcel->getActiveSheet()->setTitle('导出采购单');
    	// Set active sheet index to the first sheet, so Excel opens this as the first sheet
    	$objPHPExcel->setActiveSheetIndex(0);
    	ob_end_clean();//清除缓冲区,避免乱码
    	// excel头参数
    	header('Content-Type: application/vnd.ms-excel');
    	header('Content-Disposition: attachment;filename="导出采购单，导出时间：'.date('Ymd-His').').xls"');  //日期为文件名后缀
    	header('Cache-Control: max-age=0');
    	 
    	$objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');  //excel5为xls格式，excel2007为xlsx格式
    	$objWriter->save('php://output');
    }
    public function actionPagePrintOrder($id,$trade_id,$brand_id){
    	if(\Yii::$app->user->can('paylogistics-print')){

	    	$this->layout = 'main_small';
	    	$arr_item_model = $this->get_item_data($trade_id, $brand_id);
	    	$sales_service = $arr_item_model['sales_service'];//
	    	$user_id = $arr_item_model['user_id'];//
	    	$item_model = $arr_item_model['item_model'];
	    	foreach ($item_model as $key=>$val){
	    		$sysitem = SysItem::findOne(['id'=>$val['item_id']]);
	    		$item_model[$key]['factory_code'] = $sysitem['factory_code'];
	    	}
	    	$model=$this->findModel($id);
	    	$brand = GrpBrand::find()->with(['brandFactory'])->where("grp_brand.id={$brand_id}")->one();
	    	$trade = PayTrade::findOne(['id'=>$trade_id]);
	    	
	    	if($sales_service == 0){//平台承担售后
		    	$user = UserInfo::find()->with(['useraddress'])->where("id={$user_id}")->one();
		    	if(($user['user_type']==1 || $user['user_type']==2 || $user['user_type']==3) && $model->operation_address==''){//用户，申请VIP会员，注册VIP会员，无运营商
		    		$model->operation_address = Yii::$app->params['companyAddr'].'('.Yii::$app->params['companyContact'].')';
		    		$model->operation_photo = Yii::$app->params['companyTel'];//平台
		    	}
		    	
	    	}
	    	
	    	return $this->render('print_order',[
	    			'item_model'=>$item_model,
	    			'model'=>$model,
	    			'brand'=>$brand,
	    			'trade'=>$trade,
	    			]);
    	
    	}else{
    		throw new ForbiddenHttpException(Yii::t('app','Sorry , You don\'t have permission'));
    	}
    }
    /**
     * 解析详情，自动计算
     * @param unknown $trade_id
     * @param unknown $brand_id
     * @param string $auto_ask_cost_price
     * @return multitype:
     */
	public function get_item_data($trade_id,$brand_id,$auto_ask_cost_price=false){
		$item_model=PayLogistics::find('*,pay_logistics.number as number')->joinWith(['tradeinfo'])->joinWith(['iteminfo'])
		->where("trade_id={$trade_id} and sys_item.brand_id={$brand_id}")->all();
		$user_id = '';
		$_arr_logistics_ids = array();//更新信息的id
		$ask_cost_price = 0.00;//进价
		foreach ($item_model as $key => $val){
			$user_id = $val['tradeinfo']['user_id'];
			array_push($_arr_logistics_ids, $val['id']);//物流id集合
			$item_content = json_decode($val['tradeinfo']['content'],true);
			if(isset($item_content['singleItem']) && isset($item_content['singleItem'][0]['info']))
			{
				$sales_service=isset($item_content['singleItem'][0]['info']['sales_service'])?$item_content['singleItem'][0]['info']['sales_service']:0;
				$user_discount=isset($item_content['singleItem'][0]['info']['user_discount'])?$item_content['singleItem'][0]['info']['user_discount']:1;
			}
			
			$item_memo = json_decode($val['item_memo'],true);
			//计算进价
			$price_id = isset($item_memo['price_id']) ? intval($item_memo['price_id']):0;
			$item_id = isset($item_memo['item_id']) ? intval($item_memo['item_id']):0;
			
			$tax_rate = $val['iteminfo']['brand_name']['tax_rate'];//税率
			$tax_rate = !empty($tax_rate) ? $tax_rate : '1';//税率
			
			$item = SysItem::findOne($item_id);
			$price_base = !empty($item) ? $item['price_cost'] : 0.00;
			$price = SysItemPrices::findOne($price_id);
			$price_custom = !empty($price) ? $price['price_cost'] : 0.00;
			$cost_price = ($price_base + $price_custom) * $tax_rate;
			$ask_cost_price += $cost_price;
			
			$fab_id = isset($item_memo['sku_id']['fab'])?$item_memo['sku_id']['fab']:0;
			$mat_id = isset($item_memo['sku_id']['mat'])?$item_memo['sku_id']['mat']:0;		
			$imgs = ItemPreview::find_img_from_fab_mat($fab_id, $mat_id);
			
			$fab_img_id = !empty($imgs['fab_img'])?$imgs['fab_img']['img_small_id']:0;//面料img_id
			$fab_img_url = Image::show_image($fab_img_id);
			$mat_img_id = !empty($imgs['mat_img'])?$imgs['mat_img']['img_small_id']:0;//涂装img_id
			$mat_img_url = Image::show_image($mat_img_id);
			$preview_img_id = !empty($imgs['preview_img'])?$imgs['preview_img']['img_small_id']:0;//对应图preview_id
			$preview_img_url = Image::show_image($preview_img_id);
			
			//组合单品信息
			$item_model[$key]['fab_id']=$fab_id;
			$item_model[$key]['mat_id']=$mat_id;
			$item_model[$key]['fab_name']=isset($item_memo['sku']['fab'])?$item_memo['sku']['fab']:'';
			$item_model[$key]['fab_img_url']=$fab_img_url;
			$item_model[$key]['mat_name']=isset($item_memo['sku']['mat'])?$item_memo['sku']['mat']:'';
			$item_model[$key]['mat_img_url']=$fab_img_url;
			$item_model[$key]['preview_img_url']=$preview_img_url;
			$item_model[$key]['size']=isset($item_memo['sku']['size'])?$item_memo['sku']['size']:'';
			$item_model[$key]['light']=isset($item_memo['sku']['光源'])?$item_memo['sku']['光源']:'';
			$item_model[$key]['color']=isset($item_memo['sku']['颜色'])?$item_memo['sku']['颜色']:'';
			$item_model[$key]['name']=isset($item_memo['name'])?$item_memo['name']:'';
			$item_model[$key]['price_base']=isset($item_memo['price_base'])?$item_memo['price_base']:'0.00';
			$item_model[$key]['price_discount']=isset($item_memo['price_discount'])?$item_memo['price_discount']:'0.00';
			$item_model[$key]['price_custom']=isset($item_memo['price_custom'])?$item_memo['price_custom']:'0.00';
			$item_model[$key]['_price_discount']=isset($item_memo['_price_discount'])?$item_memo['_price_discount']:'0.00';
			$item_model[$key]['lead_time']=isset($item_memo['lead_time'])?$item_memo['lead_time']:'';
			$item_model[$key]['final_price']=isset($item_memo['final_price'])?$item_memo['final_price']:'0.00';
			$number = isset($item_memo['count'])?$item_memo['count']:'0';
			$item_model[$key]['cost_price'] = $cost_price;
			$item_model[$key]['number'] = $number;
			$item_model[$key]['cost_amount'] = floatval($cost_price) * intval($number);
			$item_model[$key]['user_discount']=isset($user_discount)?$user_discount:'';
			//更新item_memo
			$item_memo['cost_price']=$cost_price;	
			$logistics_model = PayLogistics::findOne($val['id']);
			$logistics_model->item_memo = json_encode($item_memo);//重新组合的json字符串	
			$logistics_model->save();
			$now_ask_cost_price = $val['ask_cost_price'];
			$trade_state = $val['tradeinfo']['trade_state'];
		}
		//计算ask_price_cost
		$where = implode(',', $_arr_logistics_ids);
		if(($now_ask_cost_price == '0' || $auto_ask_cost_price == true) && !in_array($trade_state, ['2','3','4'])){//只自动操作一次
			$ask_cost_price = round($ask_cost_price);
			PayLogistics::updateAll(['ask_cost_price'=>$ask_cost_price],"id in ($where)");
		}
		$return['item_model']=$item_model;
		$return['sales_service']=isset($sales_service)?$sales_service:'';
		$return['user_discount']=isset($user_discount)?$user_discount:'';
		$return['user_id']=$user_id;
		$return['_arr_logistics_ids']=$_arr_logistics_ids;
		return $return;
	}
    /**
     * Deletes an existing PayLogistics model.
     * If deletion is successful, the browser will be redirected to the 'index' page.
     * @param integer $id
     * @return mixed
     */
    public function actionDelete($id)
    {
        $this->findModel($id)->delete();

        return $this->redirect(['index']);
    }

    /**
     * Finds the PayLogistics model based on its primary key value.
     * If the model is not found, a 404 HTTP exception will be thrown.
     * @param integer $id
     * @return PayLogistics the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function findModel($id)
    {
        if (($model = PayLogistics::findOne($id)) !== null) {
        	$model->send_time_1 = $model->send_time = !empty($model->send_time) ? date('Y-m-d H:i:s',$model->send_time) : '';
        	$model->deliver_time_1 = $model->deliver_time = !empty($model->deliver_time) ? date('Y-m-d H:i:s',$model->deliver_time) : '';
            return $model;
        } else {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
    }
    
    /**
     * ajax选择类别
     * @param unknown $id
     */
    public function actionSelectoperation($operation_id)
    {
    	$operation_address = '无';
    	$operation_photo = '无';
    	$result = UserAddress::findOne(['uid'=>$operation_id]);
    	if ($result) {
    		$operation_address = $result['area'].$result['address'].' '.$result['postcode'].'('.$result['name'].')';
    		$operation_photo = $result['mobile'];
    	}
	
    	$arr_result =  array('operation_address'=>$operation_address,'operation_photo'=>$operation_photo);
    	echo  json_encode($arr_result); //以json数据返回
    
    }
    /**
     * 批量生成进价
     * @return string
     */
    public function actionGenerateAskcostprice(){
    	PayLogistics::sum_cost_price();
    	return json_encode(array('msg'=>'批量生成进价成功'));
    }
}
